随着Vue.js,React 这类视图层解决方案的流行,组件化开发的优势越来越明显。浏览器原生支持的 Web Components 再次回到人们的视野。
Web Components 包含 3 个核心技术
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| customElements.define( 'custom-element', class extends HTMLElement { constructor() { super(); } connectedCallback() { } disconnectedCallback() { } adoptedCallback() { } attributeChangedCallback() { } }, { extends: '' } );
|
需要提供宿主元素,外部的设置无法影响到其内部,而内部的设置也不会影响到外部。
1
| const shadowRoot = element.attachShadow({ mode: 'open' });
|
<template>标签可以包含 HTML 标签,不会被渲染
<slot>标签类比Vue的slot实现,提供模板占位符作用
1 2 3 4 5 6 7 8
| <template id="template"> <div> <h2>Template</h2> <slot></slot> <slot name="slot-name">DEFAULT NAME</slot> </div> </template>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| customElements.define( 'custom-element', class extends HTMLElement { constructor() { super(); let template = document.getElementById('template'); let templateContent = template.content; const shadowRoot = this.attachShadow({ mode: 'open' }).appendChild( templateContent.cloneNode(true) ); } } );
|